package org.ffmpeg.ohos.filters;

import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.render.Texture;
import ohos.agp.utils.Color;
import ohos.media.image.ImagePacker;
import ohos.media.image.PixelMap;
import ohos.media.image.common.AlphaType;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class DrawBoxVideoFilter extends OverlayVideoFilter {

	public int x;
	public int y;
	public int width;
	public int height;
	public String color;
	
	public DrawBoxVideoFilter (int x, int y, int width, int height, int alpha, String color, File tmpDir) throws Exception
	{
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		this.color = color;
		
		if( alpha < 0 || alpha > 255 ) {
			throw new IllegalArgumentException("Alpha must be an integer betweeen 0 and 255");
		}

		PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
		initializationOptions.pixelFormat = PixelFormat.ARGB_8888;
		initializationOptions.alphaType = AlphaType.PREMUL;
		initializationOptions.size = new Size(width, height);
		PixelMap temp_box = PixelMap.create(initializationOptions);

		Canvas canvas = new Canvas(new Texture(temp_box));
		canvas.drawColor(Color.getIntColor(color), Canvas.PorterDuffMode.SRC_IN);

		Paint paint = new Paint();
		paint.setAlpha(alpha);

		canvas.drawPixelMapHolder(new PixelMapHolder(temp_box), 0, 0, paint);

		File outputFile;
		outputFile = File.createTempFile("box_"+width+height+color, ".png", tmpDir);
		FileOutputStream os = new FileOutputStream(outputFile);
		ImagePacker.PackingOptions pack_options = new ImagePacker.PackingOptions();
		pack_options.format = "image/jpeg";
		pack_options.quality = 100;
		ImagePacker imagepack = ImagePacker.create();
		imagepack.initializePacking(os, pack_options);
		imagepack.addImage(temp_box);
		imagepack.finalizePacking();
		overlayFile = outputFile;
		xParam = Integer.toString(x);
		yParam = Integer.toString(y);
		
	}

	private static byte[] readResource(ohos.global.resource.Resource resource) {
		final int bufferSize = 1024;
		final int ioEnd = -1;

		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[bufferSize];
		while (true) {
			try {
				int readLen = resource.read(buffer, 0, bufferSize);
				if (readLen == ioEnd) {
					break;
				}
				output.write(buffer, 0, readLen);
			} catch (IOException e) {
				break;
			}
		}
		return output.toByteArray();
	}
}
